/*
 * (c) 2012 Leonid Bensman, lbensman.cs00@gtalumni.org
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using Yeti.WMFSdk;
using System.IO;

namespace CalcSig
{
    public class AudioHash : ItemHash
    {
        public byte[] AudioStreamHash;
        public byte[] FileHash;
    }

    class AudioHashCalculator : FileContentHashCalculator<AudioHash>
    {
        public static readonly string[] SupportedFileSearchMasks = { "*.mp3", "*.wav"  /*, "*.m4a"  */};


        public AudioHashCalculator(DirectoryEnumerator fileEnumerator)
            : base(fileEnumerator.Enumerate())
        {
        }

        protected override void OnCalculateFileHash(AudioHash itemHash)
        {
            MD5 md5 = MD5.Create();

            try
            {
                using (WmaStream wmas = new WmaStream(itemHash.Path))
                {
                    byte[] buffer = null;

                    if ((buffer == null)
                        || (buffer.Length < wmas.Length)
                        )
                    {
                        buffer = new byte[wmas.Length];
                    }

                    wmas.Read(buffer, 0, (int)wmas.Length);

                    itemHash.AudioStreamHash = md5.ComputeHash(buffer);
                }
            }
            catch (Exception e)
            {
                itemHash.AudioStreamHash = null;
                Console.WriteLine(string.Format("Exception while processing {0} for audio hash.  Exception: {1}", itemHash.Path, e.ToString()));
            }

            try
            {
                using (Stream fs = new FileStream(itemHash.Path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    itemHash.FileHash = md5.ComputeHash(fs);
                }
            }
            catch (Exception e)
            {
                itemHash.FileHash = null;
                Console.WriteLine(string.Format("Exception while processing {0} for file hash.  Exception: {1}", itemHash.Path, e.ToString()));
            }

            base.OnCalculateFileHash(itemHash);
        }
    }
}
